﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Casamiel.API.Application;
using Casamiel.API.Application.Models.Store;
using Casamiel.API.Application.Services;
using Casamiel.Application;
using Casamiel.Application.Commands.Dada;
using Casamiel.Common;
using Casamiel.Common.Extensions;
using Casamiel.Domain.Entity;
using Casamiel.Domain.Request;
using Casamiel.Domain.Request.IC;
using Casamiel.Domain.Response;
using Enyim.Caching;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NLog;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace Casamiel.API.Controllers
{
    /// <summary>
    /// tmall
    /// </summary>
    [Produces("application/json")]
    [ApiVersion("1.0")]
    [Route("api/v{api-version:apiVersion}/Tmall")]
    //[ApiVersionNeutral]
    [ApiController]
    public class TmallController : Controller
    {
        private readonly NLog.ILogger logger = NLog.LogManager.GetLogger("OrderService");
        private readonly IStoreService _storeService;
        private readonly IStoreApiService _storeApiService;
        private readonly IIcApiService _icApiService;
        private readonly ICasaMielSession _session;
        private readonly string _apitoken;
        private readonly INoticeService _notice;
        private readonly IOrderService _order;
        private readonly IMediator _mediator;
        private readonly AMapConfig _aMapConfig;
        private readonly IHttpClientFactory _clientFactory;
        private readonly string _memcachedPre;
        private readonly IMemcachedClient _memcachedClient;


        /// <summary>
        /// Initializes a new instance of the <see cref="T:Casamiel.API.Controllers.TmallController"/> class.
        /// </summary>
        /// <param name="httpClientFactory"></param>
        /// <param name="settings"></param>
        /// <param name="storeService">Store service.</param>
        /// <param name="storeApiService">Store API service.</param>
        /// <param name="iicApiService">Ic Api Service</param>
        ///<param name="session">ICasaMielSession</param>
        /// <param name="snapshot">snapshot</param>
        /// <param name="notice"></param>
        /// <param name="order"></param>
        /// <param name="memcachedClient"></param>
        /// <param name="mediator"></param>
        public TmallController(IHttpClientFactory httpClientFactory, IOptionsSnapshot<AMapConfig> settings, IStoreService storeService, IStoreApiService storeApiService, IIcApiService iicApiService,
            ICasaMielSession session, IOptionsSnapshot<CasamielSettings> snapshot, INoticeService notice, IOrderService order, IMemcachedClient memcachedClient, IMediator mediator)
        {
            if (settings == null) {
                throw new ArgumentNullException(nameof(settings));
            }

            if (snapshot == null) {
                throw new ArgumentNullException(nameof(snapshot));
            }
            _memcachedPre = snapshot.Value.MemcachedPre;
            _clientFactory = httpClientFactory;
            _aMapConfig = settings.Value;
            _storeService = storeService;
            _storeApiService = storeApiService;
            _icApiService = iicApiService;
            _session = session;
            _apitoken = snapshot.Value.ApiToken;
            _notice = notice;
            _order = order;
            _mediator = mediator;
            _memcachedClient = memcachedClient;
        }
        /// <summary>
        /// 附近门店信息.
        /// </summary>
        /// <param name="data"></param>
        /// <returns>The all store.</returns>
        /// <remarks>
        /// 纬度 、经度、距离、secret
        /// {"lat":30,"lng":12.02222,"distance":5.2,"token":""}
        /// </remarks>
        [HttpPost]
        //[HttpOptions]
        [Route("[action]")]
        public async Task<IActionResult> GetAllStore([FromBody]TmallGetAllStoreReq data)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }

            var result = await _storeApiService.CheckTokenAsync(data.Token).ConfigureAwait(false);
            if (result.Code != 0) {
                return Ok(new { code = 9999, msg = "token无效" });
            }
            //var dynamicdata = JsonConvert.DeserializeObject<JObject>(result);
            //if (dynamicdata["ResultNo"].ToString() == "00000000") {
            //    if (dynamicdata["Data"].ToString() == "0") {

            //        return Ok(new { code = 9999, msg = "token无效" });
            //    }
            //} else {
            //    return Ok(new { code = 9999, msg = "token无效" });
            //}

            //var lat = data["lat"].ToDouble(0);
            //var lng = data["lng"].ToDouble(0);
            //var distance = data["distance"].ToDouble(0);
            var en = DistanceHelper.FindNeighPosition(data.Lng, data.Lat, data.Distance);

            // var cmd = new GetAllStoreByStoreNameCommand { lat = lat, lng = lng, pageIndex = 1, pageSize =int.MaxValue, storeName ="" };
            // var result1 = await _mediator.Send(cmd).ConfigureAwait(false);
            //// var result = new { result1.Code, pageindex = result1.PageIndex, pagesize = result1.PageSize, result1.Total, result1.Content };

            //return Ok(new { result1.Code, result1.Content, result1.Msg });
            //if (lat <= 0)
            //{
            //    var storelist = await _storeService.GetStoreByNameAsync<ICasaMielSession>("", 1, 10).ConfigureAwait(false);
            //    var list = storelist.Data;
            //    return Ok(new { code = 0, content = list });
            //}
            var list1 = await _storeService.GeRectRangeAsync<ICasaMielSession>(en.MinLat, en.MinLng, en.MaxLat, en.MaxLng).ConfigureAwait(false);


            foreach (var item in list1) {
                item.Distance = DistanceHelper.GetDistance(data.Lat, data.Lng, item.Latitude, item.Longitude);// _commonService.MapService.GetGistance(a, new Map { lat=item.Latitude.ToDouble(0), lng=item.Longitude.ToDouble(0)});
            }

            var list = list1.Where(p => p.Distance < 10).Where(p=>p.IsCakeShopClose ==0).ToList();//.OrderBy(p => p.Distance).ToList();
            var count = list.Count;
            for (int i = 0; i < count; i++) {
                var distributionRadius = list[i].DistributionRadius.ToString(CultureInfo.CreateSpecificCulture("en-US")).ToDouble(0);
                //if (list[i].Distance <= distributionRadius / 1000)
                //{
                //if (list[i].IsOpenSend > 0)
                //{
                var _distance = await GetDistance(data.Lng, data.Lat, list[i].Longitude, list[i].Latitude).ConfigureAwait(false);
                list[i].Distance = _distance / 1000;
                //        if (_distance <= distributionRadius)
                //        {
                //            list[i].IsSend = true;

                //        }

                //    }
                //}
            }

            return new JsonResult(new { code = 0, content = list.OrderBy(p => p.Distance).ToList() });
        }

        private async Task<double> GetDistance(double originLng, double originLat, double soriginLng, double soriginLat)
        {
            var cachekey = $"{_memcachedPre}Dist{originLng}-{originLat}-{soriginLng}-{soriginLat}";
            var ddd = await _memcachedClient.GetValueAsync<double>(cachekey).ConfigureAwait(false);
            if (ddd >0) {
                return ddd;
            }

            var tUrl = $"{_aMapConfig.ApiUrl}/v4/direction/bicycling?origin={originLng},{originLat}&destination={soriginLng},{soriginLat}&key={_aMapConfig.ApiKey}";
            using (var requestMessage = new System.Net.Http.HttpRequestMessage(HttpMethod.Get, tUrl)) {
                using (var client = _clientFactory.CreateClient()) {
                    using (var response = await client.SendAsync(requestMessage).ConfigureAwait(false)) {
                        if (response.IsSuccessStatusCode) {
                            var result = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                            var json = JsonConvert.DeserializeObject<JObject>(result);
                            if (json["errcode"].ToString() == "0") {
                                string distance = json["data"]["paths"][0]["distance"].ToString();

                                await _memcachedClient.AddAsync(cachekey, distance.ToDouble(0), 7200).ConfigureAwait(false);
                                return distance.ToDouble(0);
                            }
                        }
                    }
                }
            }
            return 0;
        }
        /// <summary>
        /// login
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        ///<remarks>{"UserName":"","Password":""}</remarks>
        [HttpPost]
        [Route("[Action]")]
        public async Task<IActionResult> Login([FromBody] JObject data)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }

            var result = await _storeApiService.Login(data["UserName"].ToString(), data["Password"].ToString()).ConfigureAwait(false);
            var dynamicdata = JsonConvert.DeserializeObject<JObject>(result);
            if (dynamicdata["ResultNo"].ToString() == "00000000") {
                return Ok(new { code = 0, content = dynamicdata["Data"].ToString() });
            }
            return Ok(new { code = 9999, msg = dynamicdata["ResultRemark"].ToString() });
        }
        /// <summary>
        /// LogOut
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        /// <remarks>{"token":""}</remarks>
        [HttpPost]
        [Route("[Action]")]
        public async Task<IActionResult> LogOut([FromBody] JObject data)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }

            var result = await _storeApiService.LogOut(data["token"].ToString()).ConfigureAwait(false);
            var dynamicdata = JsonConvert.DeserializeObject<JObject>(result);
            if (dynamicdata["ResultNo"].ToString() == "00000000") {
                return Ok(new { code = 0, msg = "" });
            }
            return Ok(new { code = 9999, msg = dynamicdata["ResultRemark"].ToString() });
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        /// <remarks>{"token":"","title":""}</remarks>
        [HttpPost]
        [Route("[Action]")]
        public async Task<IActionResult> GetProductList([FromBody]JObject data)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }
            //int TagId, int pageindex, int pagesize
            var result = await _storeApiService.GetGoodsListForTmall(data["token"].ToString(), data["title"].ToString()).ConfigureAwait(false);
            var dynamicdata = JsonConvert.DeserializeObject<JObject>(result);
            if (dynamicdata["ResultNo"].ToString() == "00000000") {
                var entity = JsonConvert.DeserializeObject<List<GoodsGetListRsp>>(dynamicdata["Data"].ToString());
                //var pageindex = dynamicdata["PageIndex"].ToInt32(1);
                //var pagesize = dynamicdata["PageSize"].ToInt32(10);
                //var total = dynamicdata["Total"].ToInt32(0);
                var model = new { code = 0, content = entity, msg = "" };
                return Ok(model);
            }
            return Ok(new { code = 9999, msg = dynamicdata["ResultRemark"].ToString() });
        }
        /// <summary>
        /// 商品信息
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        /// <remarks>{"storeid":"1","productid":"1","token":""}</remarks>
        [HttpPost]
        [Route("[Action]")]
        public async Task<IActionResult> GetProduct([FromBody]JObject data)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }
            var result = await _storeApiService.CheckTokenAsync(data["token"].ToString()).ConfigureAwait(false);
            if (result.Code != 0) {
                return Ok(new { code = 9999, msg = "token无效" });
            }
            //var result = await _storeApiService.CheckToken(data["token"].ToString()).ConfigureAwait(false);
            //var dynamicdata = JsonConvert.DeserializeObject<JObject>(result);
            //if (dynamicdata["ResultNo"].ToString() == "00000000") {
            //    if (dynamicdata["Data"].ToString() == "0") {
            //        return Ok(new { code = 9999, msg = "token无效" });
            //    }
            //} else {
            //    return Ok(new { code = 9999, msg = "token无效" });
            //}
            //if (data["secret"].ToString() != "dsbqe1236e056f23f83e71dA")
            //{
            //	return Ok(new { code = 99999, msg = "secret无效" });
            //}
            var storeid = data["storeid"].ToInt32(0);
            var productid = data["productid"].ToInt32(0);
            if (storeid == 0) {
                return Ok(new { code = 999, msg = "storeid 有误" });
            }
            if (productid == 0) {
                return Ok(new { code = 999, msg = "productid 有误" });
            }
            var entity = await _storeApiService.GetGoodsById(data["storeid"].ToString(), data["productid"].ToString()).ConfigureAwait(false);

            IcPriceReq dto = new IcPriceReq();

            if (entity != null) {
                dto.Product = new List<ProductItemReq>();
                foreach (var item in entity.GoodsList) {
                    dto.Product.Add(new ProductItemReq { Pid = item.RelationId.ToString(CultureInfo.CurrentCulture) });

                    //Console.WriteLine(item.RelationId.ToString());
                }

                dto.Shopid = entity.StoreRelationId;

                var zmodle = await _icApiService.ProductStockQuery(dto).ConfigureAwait(false);
                if (zmodle != null) {
                    for (int i = 0; i < entity.GoodsList.Count; i++) {
                        entity.GoodsList[i].Status = 1;
                        var t = zmodle.product.Find(a => a.pid == entity.GoodsList[i].RelationId.ToString(CultureInfo.CurrentCulture));
                        if (t != null && t.icprice > 0) {
                            entity.GoodsList[i].Price = $"{t.icprice}";
                            entity.GoodsList[i].StockQuentity = t.count;
                            entity.GoodsList[i].Status = 0;
                        }
                    }
                }
            }
            var apimode = new { code = 0, content = entity };
            return new JsonResult(apimode);
        }
        /// <summary>
        /// Orders the list.
        /// </summary>
        /// <returns>The list.</returns>
        /// <param name="data">Data.</param>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> OrderList([FromBody]TmallOrderListReq data)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }
            var result = await _storeApiService.CheckTokenAsync(data.token).ConfigureAwait(false);
            if (result.Code != 0) {
                return Ok(new { code = 9999, msg = "token无效" });
            }
            var r = await _storeApiService.GetTmallOrderList(data).ConfigureAwait(false);
            var list = JsonConvert.DeserializeObject<JObject>(r);
            if (list["ResultNo"].ToString() == "00000000") {
                //var entity = JsonConvert.DeserializeObject<List<Order_BaseRsp>>(list["Data"].ToString());
                var pageindex = list["PageIndex"].ToInt32(1);
                var pagesize = list["PageSize"].ToInt32(10);
                var total = list["Total"].ToInt32(0);
                return Ok(new { code = 0, pageindex, pagesize, total, content = list["Data"].ToString() });
            }
            return Ok(new { code = 9999, msg = list["ResultRemark"].ToString() });
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("[Action]")]
        public async Task<IActionResult> CreateOrder([FromBody]TMallAddOrderReq data)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }

            var result = await _storeApiService.CheckTokenAsync(data.Token).ConfigureAwait(false);
            if (result.Code != 0) {
                return Ok(new { code = 9999, msg = "token无效" });
            }
            //var dynamicdata = JsonConvert.DeserializeObject<JObject>(result);
            //if (dynamicdata["ResultNo"].ToString() == "00000000") {
            //    if (dynamicdata["Data"].ToString() == "0") {
            //        return Ok(new { code = 9999, msg = "token无效" });
            //    }
            //} else {
            //    return Ok(new { code = 9999, msg = "token无效" });
            //}
            var storeentity = await _storeService.GetByStoreIdAsync<ICasaMielSession>(data.StoreId).ConfigureAwait(false);
            var storeRelationId = 0;
            var storeName = "";
            if (storeentity != null) {
                storeName = storeentity.StoreName;
                storeRelationId = storeentity.RelationId;
            }
            if (storeentity.IsCakeShopClose == 1) {
                return Ok(new { code = -25, msg = "门店已经闭店" });
            }
            if (data.TakeTime < DateTime.Now) {
                return Ok(new { code = -25, msg = "自提时间有误" });
            }

            IcPriceReq dto = new IcPriceReq { Shopid = storeentity.RelationId, Product = new List<ProductItemReq>() };
            for (int i = 0; i < data.GoodsList.Count; i++) {
                var goodbase = await _storeApiService.GetGoodsBase(data.StoreId, data.GoodsList[i].GoodsBaseId).ConfigureAwait(false);

                if (goodbase == null || goodbase.Status == 1) {
                    return Ok(new { code = -22, msg = "产品已经下架" });
                }
                data.GoodsList[i].RelationId = goodbase.GoodsRelationId;
                data.GoodsList[i].Title = goodbase.Title;
                if (goodbase.StockDays > 1) {
                    if (data.TakeTime.DayOfYear != DateTime.Now.DayOfYear) {
                        if (data.TakeTime.DayOfYear < DateTime.Now.AddDays(goodbase.StockDays).DayOfYear) {
                            return Ok(new { code = -28, msg = "本款蛋糕需提前2天预定" });
                        }
                    }
                }
                dto.Product.Add(new ProductItemReq { Pid = $"{goodbase.GoodsRelationId}", Count = data.GoodsList[i].GoodsQuantity });
            }

            var ictradeNO = "";
            var billNO = "";
            var icdto = new IcconsumeReq { Phoneno = data.ContactPhone, Cardno = "", Shopid = storeentity.RelationId, Pickuptime = data.TakeTime.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.CurrentCulture), Rebate = data.DiscountMoney.ToString(CultureInfo.CurrentCulture).ToDouble(0) };
            icdto.Product = new List<IcconsumeReq.IcconsumeProductItem>();
            var Orderoriginprice = 0M;

            if (DateTime.Parse(DateTime.Now.ToString("2018-05-20 20:30:00", CultureInfo.CurrentCulture), CultureInfo.CurrentCulture) < DateTime.Parse(data.TakeTime.ToString("2018-05-20 HH:mm:ss", CultureInfo.CurrentCulture), CultureInfo.CurrentCulture)) {
                return Ok(new { code = -23, msg = "抱歉该自提时间不能预定" });
            }
            if (DateTime.Now > DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd 19:30:00", CultureInfo.CurrentCulture), CultureInfo.CurrentCulture) && data.TakeTime.DayOfYear == DateTime.Now.AddDays(1).DayOfYear) {
                return Ok(new { code = -23, msg = "抱歉该时间段不能预定次日蛋糕" });
            }
            if (data.TakeTime.DayOfYear == DateTime.Now.DayOfYear) {

                var zmodle = await _icApiService.ProductStockQuery(dto).ConfigureAwait(false);
                if (zmodle != null && zmodle.product.Count > 0) {
                    for (int i = 0; i < data.GoodsList.Count; i++) {
                        var iteminfo = zmodle.product.Find(cw => cw.pid == data.GoodsList[i].RelationId.ToString(CultureInfo.CurrentCulture));
                        if (iteminfo != null) {
                            data.GoodsList[i].Price = iteminfo.icprice;
                        } else {
                            return Ok(new { code = 999, msg = $"{ data.GoodsList[i].Title},{ data.GoodsList[i].RelationId},sku不对" });
                        }

                        if (data.TakeTime.DayOfYear == DateTime.Now.DayOfYear) {
                            if (DateTime.Now > DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd 20:30:00", CultureInfo.CurrentCulture), CultureInfo.CurrentCulture) && data.TakeTime.DayOfYear == DateTime.Now.DayOfYear) {
                                return Ok(new { code = -23, msg = "抱歉该时间段不能预定当天蛋糕自提" });
                            }
                            if (storeentity.IsLimitStock == 0) {
                                if (iteminfo.count < data.GoodsList[i].GoodsQuantity) {
                                    return Ok(new { code = -21, msg = "库存不足" });
                                }
                            }
                        }
                        Orderoriginprice += data.GoodsList[i].Price * data.GoodsList[i].GoodsQuantity;
                        icdto.Product.Add(new IcconsumeReq.IcconsumeProductItem { Pid = iteminfo.pid, Count = data.GoodsList[i].GoodsQuantity });
                    }

                } else {
                    return Ok(new { code = -22, msg = "产品已经下架" });
                }


            } else {
                var iprics = await _icApiService.Icprice(dto).ConfigureAwait(false);
                if (iprics != null && iprics.Product.Count > 0) {
                    int count = data.GoodsList.Count;
                    for (int i = 0; i < count; i++) {
                        var iteminfo = iprics.Product.Find(cw => cw.Pid == $"{data.GoodsList[i].RelationId}");
                        if (iteminfo != null) {
                            data.GoodsList[i].Price = iteminfo.Icprice;
                        } else {
                            return Ok(new { code = 999, msg = $"{ data.GoodsList[i].Title},{ data.GoodsList[i].RelationId},sku不对" });
                        }
                        Orderoriginprice += data.GoodsList[i].Price * data.GoodsList[i].GoodsQuantity;
                        icdto.Product.Add(new IcconsumeReq.IcconsumeProductItem { Pid = iteminfo.Pid, Count = data.GoodsList[i].GoodsQuantity });
                    }
                } else {
                    return Ok(new { code = -22, msg = "产品已经下架" });
                }
            }



            //  var zmodle = await _icApiService.productstockquery(dto);
            //Console.WriteLine(JsonConvert.SerializeObject(zmodle));
            //if (zmodle != null && zmodle.product.Count > 0)
            //{
            //    foreach (var item in data.GoodsList)
            //    {
            //        var iteminfo = zmodle.product.Find(cw => cw.pid == item.RelationId.ToString());
            //        if (iteminfo != null)
            //        {
            //            item.Price = iteminfo.icprice;
            //        }
            //        else
            //        {
            //            return Ok(new { code = 999, msg = $"{item.Title},{item.RelationId},sku不对" });
            //        }

            //        if (DateTime.Parse(DateTime.Now.ToString("2018-05-20 20:30:00")) < DateTime.Parse(data.TakeTime.ToString("2018-05-20 HH:mm:ss")))
            //        {
            //            return Ok(new { code = -23, msg = "抱歉该自提时间不能预定" });
            //        }
            //        if (DateTime.Now > DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd 19:30:00")) && data.TakeTime.DayOfYear == DateTime.Now.AddDays(1).DayOfYear)
            //        {
            //            return Ok(new { code = -23, msg = "抱歉该时间段不能预定次日蛋糕" });
            //        }
            //        if (data.TakeTime.DayOfYear == DateTime.Now.DayOfYear)
            //        {
            //            if (DateTime.Now > DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd 20:30:00")) && data.TakeTime.DayOfYear == DateTime.Now.DayOfYear)
            //            {
            //                return Ok(new { code = -23, msg = "抱歉该时间段不能预定当天蛋糕自提" });
            //            }
            //            if (iteminfo.count < item.GoodsQuantity)
            //            {
            //                return Ok(new { code = -21, msg = "库存不足" });
            //            }
            //        }
            //        Orderoriginprice += item.Price * item.GoodsQuantity;
            //        icdto.product.Add(new IcconsumeReq.IcconsumeProductItem { pid = iteminfo.pid, count = item.GoodsQuantity });
            //    }

            //}
            //else
            //{
            //    return Ok(new { code = -22, msg = "产品已经下架" });
            //}
            
            var icentity = await _icApiService.ThirdOrder(icdto).ConfigureAwait(false);
            logger.Trace($"thirdorder,req:{JsonConvert.SerializeObject(icdto)},result:{JsonConvert.SerializeObject(icentity)}");
            if (icentity.code == 0) {
                var jobject = JsonConvert.DeserializeObject<JObject>(icentity.content);
                ictradeNO = jobject["tradeno"].ToString();
                billNO = jobject["billno"].ToString();
            } else {
                return Ok(icentity);
            }
            data.IcTradeNO = ictradeNO;
            data.BillNo = billNO;

            try {
                var result1 = await _storeApiService.AddTmallOrder(data).ConfigureAwait(false);
                var Jorder = JsonConvert.DeserializeObject<JObject>(result1);
                if (Jorder["ResultNo"].ToString() == "00000000") {
                    var model = new { code = 0, msg = "" };
                    var entity = await _order.GetByOrderCodeAsync<ICasaMielSession>(data.OrderCode).ConfigureAwait(false);
                    var pay = new IcConsumepayReq {
                        Phoneno = data.ContactPhone,

                        Shopid = storeRelationId,
                        Tradeno = ictradeNO
                    };
                    pay.Paycontent = new List<IcConsumepayReq.PaycontentItem>
                    {
                        new IcConsumepayReq.PaycontentItem
                        {
                            Paytype = "7",
                            Paymoney = (Orderoriginprice - data.DiscountMoney).ToString(CultureInfo.CurrentCulture).ToDouble(0),
                            Paytradeno = data.OrderCode
                        }
                    };
                    var zmodel = await _icApiService.Icconsumepay(pay).ConfigureAwait(false);

                    logger.Trace($"icconsumepay,req:{JsonConvert.SerializeObject(pay)},result:{JsonConvert.SerializeObject(zmodel)}");
                    if (zmodel.code == 0) {
                        using (var uow = _session.UnitOfWork(IsolationLevel.Serializable)) {
                            var noticEntity = new NoticeBaseEntity() {
                                RemindTime = DateTime.Now.AddMinutes(-3),
                                CreateTime = DateTime.Now,
                                RelationId = entity.OrderBaseId,
                                StoreId = entity.StoreId,
                                NoticeType = 0
                            };
                            await _notice.AddAsync(noticEntity, uow).ConfigureAwait(false);
                        }
                        return new JsonResult(new { code = 0, msg = "下单成功" });
                    } else if (zmodel.code == 202) {
                        pay = new IcConsumepayReq {
                            Phoneno = data.ContactPhone,
                            Shopid = storeRelationId,
                            Tradeno = ictradeNO
                        };
                        pay.Paycontent = new List<IcConsumepayReq.PaycontentItem>
                        {
                            new IcConsumepayReq.PaycontentItem
                            {
                                Paytype = "7",
                                Paymoney = (Orderoriginprice - data.DiscountMoney).ToString(CultureInfo.CurrentCulture).ToDouble(0),
                                Paytradeno = data.OrderCode + "@" + DateTime.Now.ToString("ffff", CultureInfo.CurrentCulture)
                            }
                        };
                        zmodel = await _icApiService.Icconsumepay(pay).ConfigureAwait(false);
                        logger.Trace($"icconsumepay,req:{JsonConvert.SerializeObject(pay)},result:{JsonConvert.SerializeObject(zmodel)}");
                        if (zmodel.code == 0) {
                            using (var uow = _session.UnitOfWork(IsolationLevel.Serializable)) {

                                var noticEntity = new NoticeBaseEntity() {
                                    RemindTime = DateTime.Now.AddMinutes(-3),
                                    CreateTime = DateTime.Now,
                                    RelationId = entity.OrderBaseId,
                                    StoreId = entity.StoreId,
                                    NoticeType = 0
                                };
                                await _notice.AddAsync(noticEntity, uow).ConfigureAwait(false);
                            }
                        }
                    }
                    return new JsonResult(zmodel);
                } else {
                    var req = new IcConsumeBackReq { Phoneno = data.ContactPhone, Tradeno = ictradeNO };
                    var d = await _icApiService.Icconsumeback(req).ConfigureAwait(false);
                    logger.Trace($"icconsumeback,req:{JsonConvert.SerializeObject(req)},result:{JsonConvert.SerializeObject(d)}");
                    return Ok(new { code = 9999, msg = Jorder["ResultRemark"].ToString() });
                }
            } catch {
                var req = new IcConsumeBackReq { Phoneno = data.ContactPhone, Tradeno = ictradeNO };
                var d = await _icApiService.Icconsumeback(req).ConfigureAwait(false);
                logger.Trace($"icconsumeback,req:{JsonConvert.SerializeObject(req)},result:{JsonConvert.SerializeObject(d)}");
                logger.Error($"AddTmallOrder:{JsonConvert.SerializeObject(data)}");
                throw;
            }
        }

        /// <summary>
        /// Changes the TM all dada status.
        /// </summary>
        /// <returns>The TM all dada status.</returns>
        /// <param name="req">Req.</param>
        /// <param name="token">Token.</param>
        [HttpPost]
        [Route("[Action]")]
        public async Task<BaseResult<string>> ChangeTMallDadaStatus([FromBody]ChangeDadaStatusReq req, [FromHeader(Name = "u-token")] string token)
        {
            if (req == null) {
                throw new ArgumentNullException(nameof(req));
            }

            logger.Trace($"ChangeTMallDadaStatus:{JsonConvert.SerializeObject(req)}");
            if (token != _apitoken) {
                return new BaseResult<string>(null, 99999, "token无效");
            }

            var cmd = new ChangeDataStatusCommand {
                cancel_from = req.cancel_from,
                cancel_reason = req.cancel_reason,
                dm_mobile = req.dm_mobile,
                dm_name = req.dm_name,
                order_id = req.order_id,
                order_status = req.order_status
            };
            var rsp = await _mediator.Send(cmd).ConfigureAwait(false);
            return rsp;
        }

    }
}
